'use strict';
const router = require('express').Router();
const puppeteer = require('puppeteer');
const express = require("express");

let browserWSEndpoint = null;

const expressStatic = express.static("public", {
	maxAge: 3600000
});

router.use("/", async function (req, res, next) {
	const userAgent = req.header('User-Agent')
	console.log(req.method + '[' + userAgent + '] request:' + req.url);
	const params = req.query;
	const isFile = /.js|.css|.txt|.html|.png|.ico|.svg|.jpg/.exec(req.originalUrl);
	if (isFile) {
		return expressStatic(req, res, next);
	} else {
		try {
			let needNewChrome = true;
			// TODO 查询缓存
			let url = params.url;
			if (url && needNewChrome) {
				if (!url.startsWith('http')) {
					url = 'http://' + url;
				}
				if (!browserWSEndpoint) {
					const browser = await puppeteer.launch({
						ignoreHTTPSErrors: true,
						// executablePath: '/usr/bin/google-chrome',
						executablePath: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
						headless: false,
						// args: ['--no-sandbox', '--disable-setuid-sandbox'],
					});
					browserWSEndpoint = await browser.wsEndpoint();
				}
				const browser = await puppeteer.connect({ browserWSEndpoint });
				const page = await browser.newPage();
				var getsuccess = false;
				var pagecontent = '';
				try {
					// await page.setRequestInterception(true); // 可能得升级下chrome版本，否则没法启用拦截功能
					await page.on('load', async () => {
						await page.$$eval('link[rel="stylesheet"]', (links, content) => {
							links.forEach(link => {
								const cssText = content[link.href];
								if (cssText) {
									const style = document.createElement('style');
									style.textContent = cssText;
									link.replaceWith(style);
								}
							});
						}, {});

						await page.evaluate(() => {
							var svgTags = document.getElementsByTagName('svg');
							Array.from(svgTags).forEach(svgTag => svgTag.remove());

							var stylessss = document.getElementsByTagName('style');
							Array.from(stylessss).forEach(style => style.remove());
						})
					});

					await page.on('request', async req => {
						if (req.resourceType() === 'stylesheet') {
							// await req.respond({
							// 	status: 200,
							// 	headers: {
							// 		'Access-Control-Allow-Origin': '*',
							// 	},
							// 	contentType: 'text/css',
							// 	body: '',
							// });
						} else {
							await req.continue();
						}
					});
					await page.goto(url);
					await page.waitForFunction('!console.log("abccc")');

					// await page.waitForFunction('window.isPageReady == 1');

					getsuccess = true;
					pagecontent = await page.content()
					// var regex = /<svg [\s\S]*?<\/svg>/ig;
					// var a = str.replace(regex, "");
				} catch (err) {
					// await browser.disconnect();
					console.log('出现错误：' + err); // 这里捕捉到错误 `error`
					getsuccess = false;
				} finally {
					// await page.close();
				}
				try {
					if (getsuccess && pagecontent) {
						if (!seoquery) {
							seoquery = new AV.Object('SeoQuery');
						};
						seoquery.set("Url", url);
						seoquery.set("Content", pagecontent);
						seoquery.save().then(function (todo) {
							// 异常处理
							console.log(`[保存成功] Url：${url} objectId: ${todo.id}`);
						}, function (error) {
							console.log(`[保存失败] Url：${url} message: ${error.message}`);
						});
					};
				} catch (e2) { }
				res.send(pagecontent);
				// await page.close();
			}
		} catch (e) {
			console.log("request error :", e)
			next(e);
		}
	}
});

module.exports = router;
